package com.yequan.mybatisframework.sqlsession;

import com.yequan.mybatisframework.config.BoundSql;
import com.yequan.mybatisframework.config.MappedStatement;
import com.yequan.mybatisframework.config.ParameterMapping;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;



public class PreparedStatementHandler implements StatementHandler {

	private MappedStatement mappedStatement;

	private Connection connection;

	private BoundSql boundSql;

	@Override
	public void paramize(Object paramObj) {
		try {
			// 获取预处理 statement
			PreparedStatement preparedStatement = (PreparedStatement) createStatement();
			// 设置参数，第一个参数为 sql 语句中参数的序号（从 1 开始），第二个参数为设置的

			List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();

			Class<?> parameterTypeClass = mappedStatement.getParameterTypeClass();
			
			//此次可以使用设计模式中的策略模式进行改造
			if (parameterTypeClass == Integer.class) {
				preparedStatement.setInt(1, (int) paramObj);
			} else {
				// POJO类型
				Object newInstance = parameterTypeClass.newInstance();
				for (int i = 0; i < parameterMappings.size(); i++) {
					ParameterMapping parameterMapping = parameterMappings.get(i);
					String name = parameterMapping.getName();
					
					
					Field field = parameterTypeClass.getDeclaredField(name);
					Object value = field.get(newInstance);
					
					preparedStatement.setObject(i+1, value);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Statement createStatement() {
		try {
			// 获取预处理 statement
			PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());
			return preparedStatement;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public <T> List<T> handleResult() {
		return null;
	}

}
